//
//  SquareViewController.m
//  WhatsUP
//
//  Created by itlab on 2020/11/11.
//  Copyright © 2020 Group6. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "SquareViewController.h"

//屏幕高度
#define HZKScreenH [UIScreen mainScreen].bounds.size.height
//屏幕宽度
#define HZKScreenW [UIScreen mainScreen].bounds.size.width

@implementation SquareViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        keyBoardDidShow = NO;
        isClick = NO;
        isLogin = NO;
        
        needsRefresh = YES;
        
        _animationViewArray = [[NSMutableArray alloc] init];
        _sanDianBefore = -1;
        _sanDianNow = -1;
        
    }
    return self;
}

-(void)addRefreshAnimate{
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headRefresh)];
    
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
}

-(void)viewWillAppear:(BOOL)animated {
    if(needsRefresh){
        page = 1;
        
        [self loadData];
        //创建视图对象
        _tableView = [[MyTableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height) style:UITableViewStyleGrouped];
        
        //设置代理
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
        //数据视图的头部视图的设定 UIView类型
        _tableView.tableHeaderView = nil;
        //数据视图的尾部视图
        _tableView.tableFooterView = nil;
        //去除tableview上的空白间隔
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, -1)];
        
        //隐藏滚动条
        _tableView.showsVerticalScrollIndicator = NO;
        
        //弹动
        _tableView.bounces = YES;
        
        //去除单元格间的下划线
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        //    _tableView.estimatedRowHeight = 0;
        //    _tableView.estimatedSectionFooterHeight = 0;
        //    _tableView.estimatedSectionHeaderHeight = 0;
        
        [self.view addSubview:_tableView];
        
        [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(addRefreshAnimate) userInfo:nil repeats:NO];
        
        [self.view layoutSubviews];
    } else{
        needsRefresh = YES;
    }
}

-(void)loadExtraElements{
    self.title = @"广场";
    self.navigationController.tabBarItem.title = @"广场";
    self.navigationController.tabBarItem.image = [UIImage imageNamed:@"guangchang.png"];
}

-(void) viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self.view layoutSubviews];
    self.navigationController.navigationBar.translucent = NO;

    //监听键盘的四个方法:
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardDidShow:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardDidHide:) name:UIKeyboardDidHideNotification object:nil];
    
    //添加手势，用于点击空白处收起键盘
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
    tap1.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tap1];

}

-(void)headRefresh {
    page = 1;
    [self update];
}

-(void)footerRefresh {
    page++;
    [self update];
}

//获取组数
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
    if(tableView == _tableView) {
        return _arrayContentData.count;
    }
    else {
        NSMutableArray * temp = _arrayCommentData[tableView.tag];
        return temp.count;
    }
}

//获取每组元素个数
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(tableView == _tableView) {
        return 6;
    }
    else {
        return 1;
    }
}



//获取每个单元格高度
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if(tableView == _tableView) {
        if(indexPath.row == 0) {
            return 50;
        }
        else if(indexPath.row == 1) {
            Data * data = _arrayContentData[indexPath.section];
            NSString * contentName = data.contentName;
            NSString * contentDetail = data.contentDetail;
            NSString * content = [NSString stringWithFormat:@"%@\n%@", contentName, contentDetail];
            //计算文本所需空间大小
            CGSize size = [self getSize:content];
            return size.height;
        }
        else if (indexPath.row == 2) {
            
            return imageHeight+10;
        }
        else if (indexPath.row == 3) {
            return 50;
        }
        else if (indexPath.row == 4) {
            //计算文本所需空间大小
            CGSize size = [self getSize:praisePeople];
            return size.height + 19+3;
        }
        else {
            return height+10;
        }
    }
    else {
        return commentRowSize.height + 5 + 5;
    }
    
}

//section组
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    if(tableView == _tableView) {
        /*重用机制是根据相同的标识符来重用cell的，标识符不同的cell不能彼此重用。
         于是我们将每个cell的标识符都设置为不同，就可以避免不同cell重用的问题了。
         */
        NSString *CellIdentifier = [NSString stringWithFormat:@"Cell%ld%ld", [indexPath section], [indexPath row]];//以indexPath来唯一确定cell
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        
        //列出可重用的cell
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        }
        
        //点击cell没点击阴影效果
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        if (indexPath.row == 0) {
            //设置头像
            UIImage *image = [UIImage imageNamed:@"defaultImage.png"];
            cell.imageView.layer.cornerRadius = 25;
            cell.imageView.image = image;
            cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
            cell.imageView.layer.masksToBounds = YES;
            cell.imageView.backgroundColor = [UIColor lightGrayColor];
            Data * data = [[Data alloc] init];
            data = _arrayContentData[indexPath.section];
            //用户名
            //单元格文字赋值
            cell.textLabel.text = [NSString stringWithFormat:@"%@", data.userName];
            //日期
            //设置文字子标题
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%@", [self ConvertStrToTime:data.publishTime]];
            
        }
        //内容
        else if (indexPath.row == 1) {
            UICopyLabel *label = [[UICopyLabel alloc] init];
            Data * data = [[Data alloc] init];
            data = _arrayContentData[indexPath.section];
            NSString * contentName = data.contentName;
            NSString * contentDetail = data.contentDetail;
            label.text = [NSString stringWithFormat:@"%@\n%@", contentName, contentDetail];
            label.backgroundColor = [UIColor whiteColor];
            //计算文本所需空间大小
            CGSize size = [self getSize:label.text];
            label.frame = CGRectMake(60, 0, self.view.bounds.size.width - 80, size.height);
            //多行显示，计算高度
            label.numberOfLines = 0;
            [cell.contentView addSubview:label];
            
        }
        //图片
        else if (indexPath.row == 2) {
            NSArray * imageArray = _imageMutableArray[indexPath.section];
            
            UIView * view = [[UIView alloc] init];
            view.backgroundColor = [UIColor clearColor];
            [cell.contentView addSubview:view];
            
            NSString * str = imageArray[0];
            if([str isEqualToString:@"noPicture"]) {
                imageHeight = 0.0f;
            }
            else {
                if(imageArray.count == 1) {
                    imageHeight = 230.0f;
                    UIImageView *imageView = [[UIImageView alloc] init];
                    imageView.backgroundColor = [UIColor clearColor];
                    //添加用户交互
                    imageView.userInteractionEnabled = YES;
                    //图片加载方式
                    imageView.contentMode = UIViewContentModeScaleAspectFill;
                    //图片超出部分隐藏
                    imageView.clipsToBounds = YES;
                    //添加用户点击事件
                    MyUITapGestureRecognizer *tap = [[MyUITapGestureRecognizer alloc] initWithTarget:self action:@selector(imgClick:)];
                    tap.section = indexPath.section;
                    [imageView addGestureRecognizer:tap];
                    
                    //长按实现图片保存
                    UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(imglongTapClick:)];
                    
                    [imageView addGestureRecognizer:longTap];
                    view.frame = CGRectMake(60, 10, self.view.bounds.size.width - 80, 230);
                    imageView.frame = CGRectMake(0, 0, 230, 230);
                    imageView.tag = 0;
                    [imageView sd_setImageWithURL:[NSURL URLWithString:imageArray[0]]];
                    
                    [view addSubview:imageView];
                }
                else if(imageArray.count == 2) {
                    imageHeight = 150.0f;
                    view.frame = CGRectMake(60, 10, self.view.bounds.size.width - 80, 150);
                    for(int i = 0; i < imageArray.count; i++) {
                        UIImageView *imageView = [[UIImageView alloc] init];
                        imageView.backgroundColor = [UIColor grayColor];
                        //添加用户交互
                        imageView.userInteractionEnabled = YES;
                        //图片加载方式
                        imageView.contentMode = UIViewContentModeScaleAspectFill;
                        //图片超出部分隐藏
                        imageView.clipsToBounds = YES;
                        //添加用户点击事件
                        MyUITapGestureRecognizer *tap = [[MyUITapGestureRecognizer alloc] initWithTarget:self action:@selector(imgClick:)];
                        tap.section = indexPath.section;
                        [imageView addGestureRecognizer:tap];
                        
                        //长按实现图片保存
                        UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(imglongTapClick:)];
                        
                        [imageView addGestureRecognizer:longTap];
                        imageView.frame = CGRectMake((i%2)*(5+150), (i/2)*(5+150), 150, 150);
                        imageView.tag = i;
                        [imageView sd_setImageWithURL:[NSURL URLWithString:imageArray[i]]];
                        
                        [view addSubview:imageView];
                    }
                }
                else if(imageArray.count == 3 || imageArray.count == 4) {
                    imageHeight = 120*2+5;
                    view.frame = CGRectMake(60, 10, self.view.bounds.size.width - 80, 120*2+5);
                    for(int i = 0; i < imageArray.count; i++) {
                        UIImageView *imageView = [[UIImageView alloc] init];
                        imageView.backgroundColor = [UIColor grayColor];
                        //添加用户交互
                        imageView.userInteractionEnabled = YES;
                        //图片加载方式
                        imageView.contentMode = UIViewContentModeScaleAspectFill;
                        //图片超出部分隐藏
                        imageView.clipsToBounds = YES;
                        //添加用户点击事件
                        MyUITapGestureRecognizer *tap = [[MyUITapGestureRecognizer alloc] initWithTarget:self action:@selector(imgClick:)];
                        tap.section = indexPath.section;
                        [imageView addGestureRecognizer:tap];
                        
                        //长按实现图片保存
                        UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(imglongTapClick:)];
                        
                        [imageView addGestureRecognizer:longTap];
                        imageView.frame = CGRectMake((i%2)*(5+120), (i/2)*(5+120), 120, 120);
                        imageView.tag = i;
                        [imageView sd_setImageWithURL:[NSURL URLWithString:imageArray[i]]];
                        
                        [view addSubview:imageView];
                    }
                }
                else if(imageArray.count == 5 || imageArray.count == 6) {
                    imageHeight = 100*2+5;
                    view.frame = CGRectMake(60, 10, self.view.bounds.size.width - 80, 100*2+5);
                    for(int i = 0; i < imageArray.count; i++) {
                        UIImageView *imageView = [[UIImageView alloc] init];
                        imageView.backgroundColor = [UIColor grayColor];
                        //添加用户交互
                        imageView.userInteractionEnabled = YES;
                        //图片加载方式
                        imageView.contentMode = UIViewContentModeScaleAspectFill;
                        //图片超出部分隐藏
                        imageView.clipsToBounds = YES;
                        //添加用户点击事件
                        MyUITapGestureRecognizer *tap = [[MyUITapGestureRecognizer alloc] initWithTarget:self action:@selector(imgClick:)];
                        tap.section = indexPath.section;
                        [imageView addGestureRecognizer:tap];
                        
                        //长按实现图片保存
                        UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(imglongTapClick:)];
                        
                        [imageView addGestureRecognizer:longTap];
                        imageView.frame = CGRectMake((i%3)*(5+100), (i/3)*(5+100), 100, 100);
                        imageView.tag = i;
                        [imageView sd_setImageWithURL:[NSURL URLWithString:imageArray[i]]];
                        
                        [view addSubview:imageView];
                    }
                }
                else {
                    imageHeight = 80*3+5+5;
                    view.frame = CGRectMake(60, 10, self.view.bounds.size.width - 80, 80*3+5+5);
                    for(int i = 0; i < imageArray.count; i++) {
                        UIImageView *imageView = [[UIImageView alloc] init];
                        imageView.backgroundColor = [UIColor grayColor];
                        //添加用户交互
                        imageView.userInteractionEnabled = YES;
                        //图片加载方式
                        imageView.contentMode = UIViewContentModeScaleAspectFill;
                        //图片超出部分隐藏
                        imageView.clipsToBounds = YES;
                        //添加用户点击事件
                        MyUITapGestureRecognizer *tap = [[MyUITapGestureRecognizer alloc] initWithTarget:self action:@selector(imgClick:)];
                        tap.section = indexPath.section;
                        [imageView addGestureRecognizer:tap];
                        
                        //长按实现图片保存
                        UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(imglongTapClick:)];
                        
                        [imageView addGestureRecognizer:longTap];
                        imageView.frame = CGRectMake((i%3)*(5+80), (i/3)*(5+80), 80, 80);
                        imageView.tag = i;
                        [imageView sd_setImageWithURL:[NSURL URLWithString:imageArray[i]]];
                        
                        [view addSubview:imageView];
                    }
                }
            }
            
        }
        //点赞、评论、下载、收藏按钮
        else if (indexPath.row == 3) {
            UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"sangedian.png"]];
            
            UIButton *btnAll = [UIButton buttonWithType:UIButtonTypeCustom];
            btnAll.frame = CGRectMake(self.view.bounds.size.width - 32 -20-2, 8, image.size.width+4, image.size.height-8);
            //设置圆角边框
            btnAll.layer.cornerRadius = 3;
            btnAll.layer.masksToBounds = YES;
            btnAll.backgroundColor = [UIColor colorWithRed:225.0/255 green:225.0/255 blue:225.0/255 alpha:1];
            //图片居中显示，图片不变形
            btnAll.contentMode = UIViewContentModeCenter;
            //超过imageView的图片不显示
            btnAll.clipsToBounds = YES;
            //为按钮添加图片
            [btnAll setImage:image forState:UIControlStateNormal];
            
            [cell.contentView addSubview:btnAll];
            btnAll.tag = indexPath.section;
            NSLog(@"section%ld", indexPath.section);
            [btnAll addTarget:self action:@selector(pressLogal:) forControlEvents:UIControlEventTouchUpInside];
            
            
            //  动画缩放开始的点
            _animationPoint = CGPointMake(self.view.bounds.size.width - 32 -20-4-15, 5);
            //动画view
            _animationView = [[UIView alloc] initWithFrame:CGRectMake(self.view.bounds.size.width - 32 -20-4-15 - 32*4 - 5*20, 5, 32*4+5*20, 40)];
            _animationView.backgroundColor = [UIColor colorWithRed:200.0/255 green:200.0/255 blue:200.0/255 alpha:1];
            _animationView.layer.cornerRadius = 5.0f;
            _animationView.alpha = 0.0f;
            
            if(_animationViewArray.count == indexPath.section) {
                [_animationViewArray addObject:_animationView];
            }
            
            [cell.contentView addSubview:_animationView];
            
            //添加点赞、评论、收藏、下载按钮
            for(int i = 0; i < 4; i++) {
                NSNumber * isPriase = isPraiseArray[indexPath.section];
                NSNumber * isComment = isCommentArray[indexPath.section];
                NSNumber * isCollect = isCollectArray[indexPath.section];
                NSNumber * isDownload = isDownloadArray[indexPath.section];
                UIImage *image1 = [[UIImage alloc] init];
                if((i == 0 && [isPriase isEqual: @YES]) || (i == 1 && [isComment isEqual:@YES]) || (i == 2 && [isCollect isEqual:@YES]) || (i == 3 && [isDownload isEqual:@YES]) ) {
                    image1 = [UIImage imageNamed:[NSString stringWithFormat:@"%d-%d.png", (i+1)*11, i+1]];
                }
                else {
                    image1 = [UIImage imageNamed:[NSString stringWithFormat:@"%d.png", (i+1)*11]];
                }
                MyButton *btn = [MyButton buttonWithType:UIButtonTypeCustom];
                btn.frame = CGRectMake(20+i*(32+20), 4, 32, 32);
                [btn setImage:image1 forState:UIControlStateNormal];
                [_animationView addSubview:btn];
                
                btn.tag = 101 + i;
                btn.section = indexPath.section;
                btn.row = indexPath.row;
                
                [btn addTarget:self action:@selector(pressBtn:) forControlEvents:UIControlEventTouchUpInside];
            }
        }
        //点赞人显示
        else if (indexPath.row == 4) {
            praisePeople = @"♡ ";
            NSMutableArray * eachPraisePeople = _praisePeople[indexPath.section];
            for(int i = 0; i < eachPraisePeople.count; i++) {
                NSString * strName = eachPraisePeople[i];
                if(i == eachPraisePeople.count-1) {
                    praisePeople = [praisePeople stringByAppendingFormat:@"%@", strName];
                }
                else {
                    praisePeople = [praisePeople stringByAppendingFormat:@"%@, ", strName];
                }
            }
            
            MyUILabel *label = [[MyUILabel alloc] init];
            label.text = praisePeople;
            label.textColor = [UIColor colorWithRed:0.0/255 green:102.0/255 blue:204.0/255 alpha:1];
            label.font = [UIFont systemFontOfSize:15];
            label.backgroundColor = [UIColor colorWithRed:235.0/255 green:235.0/255 blue:235.0/255 alpha:1];
            //设置圆角边框
            label.layer.cornerRadius = 4;
            label.layer.masksToBounds = YES;
            //计算文本所需空间大小
            CGSize size = [self getSize:label.text];
            label.frame = CGRectMake(60, 0, self.view.bounds.size.width - 80, size.height + 19);
            //多行显示，计算高度
            label.numberOfLines = 0;
            
            [cell.contentView addSubview:label];
        }
        //评论
        else if (indexPath.row == 5) {
            height = 0.0f;
            
            NSMutableArray * commentAndReplyArray = _arrayCommentData[indexPath.section];
            for(int i = 0; i < commentAndReplyArray.count; i++) {
                CommentData * commentData = commentAndReplyArray[i];
                if([commentData.haveComment isEqualToString:@"YES"]) {
                    NSString * strName = [[NSString alloc] init];
                    if([commentData.isReply isEqualToString:@"NO"]) {
                        strName = [NSString stringWithFormat:@"%@: ", commentData.commentUserName];
                    }
                    else {
                        strName = [NSString stringWithFormat:@"%@ 回复 %@: ", commentData.commentUserName, commentData.replyFatherName];
                    }
                    NSString * strComment = commentData.commentContent;
                    //转为富文本
                    NSMutableAttributedString * noteStr = [self setRichTextOfName:strName setRichTextOfComment:strComment];
                    //计算富文本的大小
                    CGRect labelRect = [self getRect:noteStr];
                    height += (labelRect.size.height + 5 + 5);
                }
            }
            
            _commentTableView = [[MyTableView alloc] initWithFrame:CGRectMake(60, 0, self.view.frame.size.width - 60 - 20, height)];
            
            //设置代理
            _commentTableView.delegate = self;
            _commentTableView.dataSource = self;
            //不可弹动
            _commentTableView.scrollEnabled = NO;
            
            _commentTableView.layer.cornerRadius = 3;
            _commentTableView.layer.masksToBounds = YES;
            
            _commentTableView.backgroundColor = [UIColor colorWithRed:235.0/255 green:235.0/255 blue:235.0/255 alpha:1];
            
            _commentTableView.tag = indexPath.section;
            
            _commentTableView.row = indexPath.row;
            _commentTableView.section = indexPath.section;
            
            _commentTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
            
            [cell.contentView addSubview:_commentTableView];
            
            
        }
        
        return cell;
    }
    else {
        /*重用机制是根据相同的标识符来重用cell的，标识符不同的cell不能彼此重用。
         于是我们将每个cell的标识符都设置为不同，就可以避免不同cell重用的问题了。
         */
        NSString *CellIdentifier = [NSString stringWithFormat:@"commentCell%ld%ld", [indexPath section], [indexPath row]];//以indexPath来唯一确定cell
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        
        //列出可重用的cell
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:CellIdentifier];
        }
        
        //点击cell没点击阴影效果
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        NSMutableArray * commentAndReplyArray = _arrayCommentData[tableView.tag];
        CommentData * commentData = commentAndReplyArray[indexPath.section];
        if([commentData.haveComment isEqualToString:@"YES"]) {
            NSString * strName = [[NSString alloc] init];
            if([commentData.isReply isEqualToString:@"NO"]) {
                strName = [NSString stringWithFormat:@"%@: ", commentData.commentUserName];
            }
            else {
                strName = [NSString stringWithFormat:@"%@ 回复 %@: ", commentData.commentUserName, commentData.replyFatherName];
            }
            NSString * strComment = commentData.commentContent;
            //转为富文本
            NSMutableAttributedString * noteStr = [self setRichTextOfName:strName setRichTextOfComment:strComment];
            //计算富文本的大小
            CGRect labelRect = [self getRect:noteStr];
            
            commentRowSize = labelRect.size;
            UICopyLabel * label = [[UICopyLabel alloc] initWithFrame:CGRectMake(7, 5, commentRowSize.width, commentRowSize.height)];
            label.attributedText = noteStr;
            //label.font = [UIFont systemFontOfSize:15];
            //多行显示
            label.numberOfLines = 0;
            
            cell.backgroundColor = [UIColor clearColor];
            
            label.tag = indexPath.row;
            
            [cell.contentView addSubview:label];
        }
        
        return cell;
    }
    
}

//获取每组头部高度
-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if(tableView == _tableView) {
        return 0.5;
    }
    else {
        return 0;
    }
}

//获取每组尾部高度
-(CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if(tableView == _tableView) {
        return 0.5;
    }
    else {
        return 0;
    }
}

//修改头部标题颜色
-(UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 0)];
    headerView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
    return headerView;
}

//修改尾部标题颜色
-(UIView *) tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 0.1)];
    headerView.backgroundColor = [UIColor grayColor];
    return headerView;
}

//选中单元格调用此协议函数
-(void) tableView:(MyTableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    if(tableView == _tableView) {
        NSLog(@"选中tabkeView单元格 %ld, %ld", indexPath.section, indexPath.row);
    }
    else {
        NSLog(@"选中commentTabkeView单元格 %ld, %ld", indexPath.section, indexPath.row);
        
        isClick = YES;
        
        UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
        
        UICopyLabel * textLabel = [[UICopyLabel alloc] init];
        
        for(UICopyLabel * label in cell.contentView.subviews) {
            if(label.tag == 0) {
                textLabel = label;
            }
        }
        
        NSRange range1 = [textLabel.text rangeOfString:@":"];
        NSRange range2 = [textLabel.text rangeOfString:@" 回复 "];
        if(range1.location != NSNotFound) {
            if(range2.location == NSNotFound) {
                NSString * string = [textLabel.text substringWithRange:NSMakeRange(0, range1.location)];
                
                _cellSelectDic = [[NSMutableDictionary alloc] init];
                
                NSNumber * section = [NSNumber numberWithInteger:tableView.section];
                NSNumber * row = [NSNumber numberWithInteger:tableView.row];
                NSNumber * commentSection = [NSNumber numberWithInteger:indexPath.section];
                [_cellSelectDic setObject:section forKey:@"section"];
                [_cellSelectDic setObject:row forKey:@"row"];
                [_cellSelectDic setObject:commentSection forKey:@"commentSection"];
                [_cellSelectDic setObject:string forKey:@"name"];
                
                if ([string isEqualToString:iphoneUserName]) {
                    [textLabel becomeFirstResponder];
                    UIMenuItem *cutLink = [[UIMenuItem alloc] initWithTitle:@"删除" action:@selector(menuCutBtnPressed:)];
                    
                    UIMenuController * menuController = [UIMenuController sharedMenuController];
                    menuController.menuItems = @[cutLink];
                    [menuController setTargetRect:textLabel.frame inView:textLabel.superview];
                    [menuController setMenuVisible:YES animated: YES];
                }
                else {
                    [textLabel becomeFirstResponder];
                    UIMenuItem *dianZan = [[UIMenuItem alloc] initWithTitle:@"点赞/取消" action:@selector(dianZanPressed:)];
                    UIMenuItem *reply = [[UIMenuItem alloc] initWithTitle:@"回复" action:@selector(replyPress:)];
                    
                    UIMenuController * menuController = [UIMenuController sharedMenuController];
                    menuController.menuItems = @[dianZan, reply];
                    [menuController setTargetRect:textLabel.frame inView:textLabel.superview];
                    [menuController setMenuVisible:YES animated: YES];
                    
                    
                    
                    
//                    NSString * huifu = [NSString stringWithFormat:@"回复%@:",string];
//
//                    UIView *keyBoardTopView = [[UIView alloc] initWithFrame:CGRectMake(0, HZKScreenH, HZKScreenW, 50)];
//                    keyBoardTopView.backgroundColor = [UIColor colorWithRed:214.0/255 green:214.0/255 blue:214.0/255 alpha:1];
//                    keyBoardTopView.layer.borderWidth = 0.7;
//                    keyBoardTopView.layer.borderColor = [[UIColor colorWithRed:235.0/255 green:235.0/255 blue:235.0/255 alpha:1] CGColor];
//
//                    //输入框
//                    UITextField *inputTF = [[UITextField alloc] init];
//                    inputTF.frame = CGRectMake(10, 6, HZKScreenW - 10 - 76, 38);
//                    inputTF.placeholder = huifu;
//                    inputTF.tag = 1001;
//                    //设置代理
//                    inputTF.delegate = (id)self;
//                    inputTF.layer.cornerRadius = 4;
//                    inputTF.layer.masksToBounds = YES;
//                    self.commentTF = inputTF;
//                    inputTF.backgroundColor = [UIColor whiteColor];
//                    //监听textfield的输入
//                    [inputTF addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
//
//                    [keyBoardTopView addSubview:inputTF];
//                    //让UITextField直接进入编辑状态
//                    [inputTF becomeFirstResponder];
//
//                    //发布按钮
//                    sendBtn = [[MyButton alloc] initWithFrame:CGRectMake(keyBoardTopView.bounds.size.width - 60 - 9, 7, 60, 36)];
//                    sendBtn.titleLabel.font = [UIFont boldSystemFontOfSize:17];
//                    [sendBtn setTitle:@"发布" forState:UIControlStateNormal];
//                    sendBtn.tag = 2002;
//                    sendBtn.backgroundColor = [UIColor clearColor];
//                    sendBtn.layer.borderColor = [[UIColor colorWithRed:100.0/255 green:100.0/255 blue:100.0/255 alpha:1] CGColor];
//                    sendBtn.layer.borderWidth = 0.5;
//                    sendBtn.layer.cornerRadius = 4;
//                    sendBtn.enabled = NO;
//                    [sendBtn setTitleColor:[UIColor colorWithRed:100.0/255 green:100.0/255 blue:100.0/255 alpha:1] forState:UIControlStateNormal];
//                    sendBtn.section = tableView.section;
//                    sendBtn.row = indexPath.section;
//                    sendBtn.responseTo = string;
//
//                    [sendBtn addTarget:self action:@selector(dismissKeyboard:) forControlEvents:UIControlEventTouchUpInside];
//                    [keyBoardTopView addSubview:sendBtn];
//
//                    self.commentView = keyBoardTopView;
//                    [self.view.superview addSubview:keyBoardTopView];
                }
            }
            
        }
        
        
    }
    
}
//取消选中单元格调用此协议函数
-(void) tableView:(UITableView *) tableView didDeselectRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    if(tableView == _tableView) {
        NSLog(@"取消选中tabkeView单元格 %ld, %ld", indexPath.section, indexPath.row);
    }
    else {
        NSLog(@"取消选中commentTabkeView单元格 %ld, %ld", indexPath.section, indexPath.row);
    }
}

//计算文本大小以确定UILabel高度
-(CGSize) getSize : (NSString *)text {
    CGSize size;
    if([[text substringWithRange:NSMakeRange(0, 1)] isEqualToString:@"♡"]) {
        size = [text boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width - 80 - 16, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]} context:nil].size;
    }
    else {
        size = [text boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width - 80 - 16, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:18]} context:nil].size;
    }
    
    return size;
}

//计算富文本的大小以确定UILabel的高度
-(CGRect) getRect : (NSMutableAttributedString *) noteStr {
    NSStringDrawingOptions options = NSStringDrawingUsesLineFragmentOrigin;
    CGRect labelRect = [noteStr boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width - 80 - 16, CGFLOAT_MAX) options:options context:nil];
    return labelRect;
}


-(void)imglongTapClick:(UILongPressGestureRecognizer*)gesture
{
    if(gesture.state == UIGestureRecognizerStateBegan)
    {
        UIImageView *img = (UIImageView *)[gesture view];
        
        _sentImg = img;
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"保存图片" message:@"保存图片到手机" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *_Nonnull action) {
            NSLog(@"点击了取消按钮");
        }];
        UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"保存" style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) {
            NSLog(@"点击了确定按钮");
            UIImageWriteToSavedPhotosAlbum(self->_sentImg.image,self,@selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:),nil);
        }];
        
        
        [alertController addAction:cancelAction];
        [alertController addAction:OKAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
        
    }
    
}


- (void)imageSavedToPhotosAlbum:(UIImage*)image didFinishSavingWithError:  (NSError*)error contextInfo:(void*)contextInfo

{
    NSString*message =@"成功保存到相册";
    if(!error) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) {
            NSLog(@"点击了确定按钮");
        }];
        
        [alertController addAction:OKAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
        
    } else
    {
        message = [error description];
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *OKAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) {
            NSLog(@"点击了确定按钮");
        }];
        
        [alertController addAction:OKAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
        
    }
    
}


//通过滑动屏幕隐藏点赞等的框
-(void) scrollViewDidScroll:(UIScrollView *)scrollView {
    if(_sanDianNow != -1) {
        CGFloat offsetX = _animationPoint.x - self.view.frame.size.width / 2 - 20;
        CGFloat offsetY = _animationPoint.y - _animationView.frame.size.height / 2;
        UIView *view = _animationViewArray[_sanDianNow];
        if (view.alpha != 0.0f) {
            [self bigToSmall:view offsetOfX:offsetX offsetOfY:offsetY];
        }
    }
    if(keyBoardDidShow) {
        [_commentTF endEditing:YES];
    }
}

//点击三个点显示点赞、评论、收藏、下载按钮
-(void) pressLogal : (UIButton *) btn {
    NSLog(@"被点击的三点%ld", btn.tag);
    //X、Y轴的偏移
    CGFloat offsetX = _animationPoint.x - self.view.frame.size.width / 2 - 20;
    CGFloat offsetY = _animationPoint.y - _animationView.frame.size.height / 2;
    
    UIView *view = [[UIView alloc] init];
    
    if(_sanDianBefore == -1) {
        _sanDianBefore = btn.tag;
        _sanDianNow = btn.tag;
        view = _animationViewArray[_sanDianNow];
        NSLog(@"stpe1 before%ld", _sanDianBefore);
        NSLog(@"now%ld", _sanDianNow);
        NSLog(@"arraycount%ld", _animationViewArray.count);
        //动画由小到大
        [self smallToBig:view offsetOfX:offsetX offsetOfY:offsetY];
    }
    else if(_sanDianBefore != -1 && _sanDianBefore == btn.tag) {
        _sanDianNow = btn.tag;
        NSLog(@"stpe2 before%ld", _sanDianBefore);
        NSLog(@"now%ld", _sanDianNow);
        NSLog(@"arraycount%ld", _animationViewArray.count);
        view = _animationViewArray[_sanDianNow];
        //动画由小到大
        if(view.alpha == 0.0f) {
            [self smallToBig:view offsetOfX:offsetX offsetOfY:offsetY];
        }
        //动画由大到小
        else {
            [self bigToSmall:view offsetOfX:offsetX offsetOfY:offsetY];
        }
        
    }
    else if(_sanDianBefore != -1 && _sanDianBefore != btn.tag){
        _sanDianNow = btn.tag;
        NSLog(@"stpe3 before%ld", _sanDianBefore);
        NSLog(@"now%ld", _sanDianNow);
        view = _animationViewArray[_sanDianNow];
        NSLog(@"arraycount%ld", _animationViewArray.count);
        //动画由小到大
        if(view.alpha == 0.0f) {
            [self smallToBig:view offsetOfX:offsetX offsetOfY:offsetY];
        }
        //动画由大变小
        else {
            [self bigToSmall:view offsetOfX:offsetX offsetOfY:offsetY];
        }
        
        //隐藏上一个被点开的 三点 图标
        UIView *viewBefore = _animationViewArray[_sanDianBefore];
        if(viewBefore.alpha == 1.0f) {
            [self bigToSmall:viewBefore offsetOfX:offsetX offsetOfY:offsetY];
        }
        
        _sanDianBefore = _sanDianNow;
    }
    
}

//动画由小到大
-(void) smallToBig : (UIView *) view offsetOfX : (CGFloat)offsetX offsetOfY : (CGFloat)offsetY {
    view.transform = CGAffineTransformMake(0.01, 0, 0, 0.01, offsetX, offsetY);
    
    [UIView animateWithDuration:0.3f animations:^{
        view.alpha = 1.0f;
        view.transform = CGAffineTransformMake(1.05f, 0, 0, 1.0f, 0, 0);
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.1f animations:^{
            view.transform = CGAffineTransformMake(1, 0, 0, 1, 0, 0);
        } completion:^(BOOL finished) {
            //恢复原位
            view.transform = CGAffineTransformIdentity;
        }];
    }];
}

//动画由大到小
-(void) bigToSmall : (UIView *) view offsetOfX : (CGFloat)offsetX offsetOfY : (CGFloat)offsetY {
    view.transform = CGAffineTransformMake(1, 0, 0, 1, 0, 0);
    [UIView animateWithDuration:0.2 animations:^{
        view.transform = CGAffineTransformMake(0.01, 0, 0, 0.01, offsetX, offsetY);
    }completion:^(BOOL finished) {
        view.transform = CGAffineTransformIdentity;
        view.alpha = 0.0f;
    }];
}

-(void) pressBtn : (MyButton *) btn {
    UIView * view = btn.superview;
    CGFloat offsetX = _animationPoint.x - self.view.frame.size.width / 2 - 20;
    CGFloat offsetY = _animationPoint.y - _animationView.frame.size.height / 2;
    [self bigToSmall:view offsetOfX:offsetX offsetOfY:offsetY];
    
    NSNumber * isPraise = isPraiseArray[btn.section];
    //NSNumber * isComment = isCommentArray[btn.section];
    NSNumber * isCollect = isCollectArray[btn.section];
    NSNumber * isDownload = isDownloadArray[btn.section];
    
    if(btn.tag == 101) {
        NSString *strName = iphoneUserName;
        _eachPraisePeople = _praisePeople[btn.section];
        Data * data = _arrayContentData[btn.section];
        NSString *url = [NSString stringWithFormat:@"http://172.18.178.56/api/like/%@", data.contentID];
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@YES, @"isContent", @NO, @"isComment", @NO, @"isReply", nil];
        if([isPraise isEqual:@NO]) {
            NSLog(@"点赞");
            UIImage *image = [UIImage imageNamed:@"11-1.png"];
            [btn setImage:image forState:UIControlStateNormal];
            NSNumber * isPraise1 = @YES;
            [isPraiseArray replaceObjectAtIndex:btn.section withObject:isPraise1];
            
            [_eachPraisePeople addObject:strName];
            
            NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
            NSString* jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:120];
            [request setHTTPMethod:@"POST"];
            [request setValue: @"application/json; encoding=utf-8" forHTTPHeaderField:@"Content-Type"];
            [request setValue: @"application/json" forHTTPHeaderField:@"Accept"];
            [request setHTTPBody: [jsonString dataUsingEncoding:NSUTF8StringEncoding]];
            
            AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            [[manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                if (!error && responseObject) {
                    NSArray *list = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                    NSLog(@"点赞 = %@", list);
                } else {
                    NSLog(@"false");
                }
            }] resume];
            
        }
        else {
            NSLog(@"取消点赞");
            UIImage *image = [UIImage imageNamed:@"11.png"];
            [btn setImage:image forState:UIControlStateNormal];
            NSNumber * isPraise1 = @NO;
            [isPraiseArray replaceObjectAtIndex:btn.section withObject:isPraise1];
            
            [_eachPraisePeople removeObject:strName];
            
            AFHTTPSessionManager * manage = [AFHTTPSessionManager manager];
            //设置请求体为JSON
            manage.requestSerializer = [AFJSONRequestSerializer serializer];
            //设置响应体为JSON
            manage.responseSerializer = [AFJSONResponseSerializer serializer];
            [manage PATCH:url parameters:dict headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                if([responseObject isKindOfClass:[NSDictionary class]]) {
                    NSLog(@"取消点赞 = %@", responseObject);
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                NSLog(@"取消点赞失败");
            }];
        }
        //替换修改的数组
        [_praisePeople replaceObjectAtIndex:btn.section withObject:_eachPraisePeople];
        //只更新一个cell
//        NSIndexPath * indexPath = [NSIndexPath indexPathForRow:btn.row+1 inSection:btn.section];
//        [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        [_tableView reloadData];
        
    }
    //点击评论按钮弹出评论文本框和键盘
    else if(btn.tag == 102) {
        NSLog(@"评论");
        //UIImage *image = [UIImage imageNamed:@"22-2.png"];
        //[btn setImage:image forState:UIControlStateNormal];
        //isComment[btn.section] = YES;
        
        UIView *keyBoardTopView = [[UIView alloc] initWithFrame:CGRectMake(0, HZKScreenH, HZKScreenW, 50)];
        keyBoardTopView.backgroundColor = [UIColor colorWithRed:214.0/255 green:214.0/255 blue:214.0/255 alpha:1];
        keyBoardTopView.layer.borderWidth = 0.7;
        keyBoardTopView.layer.borderColor = [[UIColor colorWithRed:235.0/255 green:235.0/255 blue:235.0/255 alpha:1] CGColor];
        
        //输入框
        UITextField *inputTF = [[UITextField alloc] init];
        inputTF.frame = CGRectMake(10, 6, HZKScreenW - 10 - 76, 38);
        inputTF.placeholder = @"请输入评论";
        inputTF.tag = 1001;
        //设置代理
        inputTF.delegate = (id)self;
        inputTF.layer.cornerRadius = 4;
        inputTF.layer.masksToBounds = YES;
        self.commentTF = inputTF;
        inputTF.backgroundColor = [UIColor whiteColor];
        //监听textfield的输入
        [inputTF addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
        
        [keyBoardTopView addSubview:inputTF];
        //让UITextField直接进入编辑状态
        [inputTF becomeFirstResponder];
        
        //发布按钮
        sendBtn = [[MyButton alloc] initWithFrame:CGRectMake(keyBoardTopView.bounds.size.width - 60 - 9, 7, 60, 36)];
        sendBtn.titleLabel.font = [UIFont boldSystemFontOfSize:17];
        [sendBtn setTitle:@"发布" forState:UIControlStateNormal];
        sendBtn.tag = 2002;
        sendBtn.backgroundColor = [UIColor clearColor];
        sendBtn.layer.borderColor = [[UIColor colorWithRed:100.0/255 green:100.0/255 blue:100.0/255 alpha:1] CGColor];
        sendBtn.layer.borderWidth = 0.5;
        sendBtn.layer.cornerRadius = 4;
        sendBtn.enabled = NO;
        [sendBtn setTitleColor:[UIColor colorWithRed:100.0/255 green:100.0/255 blue:100.0/255 alpha:1] forState:UIControlStateNormal];
        sendBtn.section = btn.section;
        sendBtn.row = btn.row;
        [sendBtn addTarget:self action:@selector(dismissKeyboard:) forControlEvents:UIControlEventTouchUpInside];
        [keyBoardTopView addSubview:sendBtn];
        
        self.commentView = keyBoardTopView;
        [self.view.superview addSubview:keyBoardTopView];
        
    }
    else if(btn.tag == 103) {
        NSNumber * isCollect1 = [[NSNumber alloc] init];
        if([isCollect isEqual:@NO]) {
            NSLog(@"收藏");
            UIImage *image = [UIImage imageNamed:@"33-3.png"];
            [btn setImage:image forState:UIControlStateNormal];
            isCollect1 = @YES;
        }
        else {
            NSLog(@"取消收藏");
            UIImage *image = [UIImage imageNamed:@"33.png"];
            [btn setImage:image forState:UIControlStateNormal];
            isCollect1 = @NO;
        }
        [isCollectArray replaceObjectAtIndex:btn.section withObject:isCollect1];
    }
    else if(btn.tag == 104) {
        NSLog(@"下载");
        UIImage *image = [UIImage imageNamed:@"44-4.png"];
        [btn setImage:image forState:UIControlStateNormal];
        isDownload = @YES;
        [isDownloadArray replaceObjectAtIndex:btn.section withObject:isDownload];
    }

}

//点击图片 放大
-(void)imgClick : (MyUITapGestureRecognizer *) ges
{
    UIImageView *imageView = (UIImageView *)ges.view;
    NSInteger index = imageView.tag;
    num = imageView.superview.subviews.count;
    section = ges.section;
    _saveImg = imageView.image;
    //创建MWPhotoBrowser ，要使用initWithDelegate方法，要遵循MWPhotoBrowserDelegate协议
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc]initWithDelegate:self];
    //设置当前要显示的图片
    [browser setCurrentPhotoIndex:index];
    //显示导航条
    self.navigationController.navigationBar.hidden = NO;
    browser.navigationController.navigationBar.hidden = NO;
    //分享按钮,默认是
    browser.displayActionButton =YES;
    //左右分页切换,默认否
    browser.displayNavArrows = NO;
    //是否显示选择按钮（右上方的按钮）在图片上,默认否
    browser.displaySelectionButtons = NO;
    //控制条件控件是否显示,默认否
    browser.alwaysShowControls = YES;
    //是否全屏,默认是
    browser.zoomPhotosToFill = YES;
    // 设置不需要刷新
    needsRefresh = NO;
    //push到MWPhotoBrowser
    [self.navigationController pushViewController:browser animated:YES];
}

//图片的个数
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser{
    
    return num;
}

//通过下标获取图片
- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index{
    
    //创建图片模型
    MWPhoto *ph = [MWPhoto photoWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",_imageMutableArray[section][index]]]];
    //图片添加长按手势
    UILongPressGestureRecognizer *lpGes = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressAction:)];
    [photoBrowser.view addGestureRecognizer:lpGes];
    
    return ph;
    
}

//获取当前点击的图片
-(void)photoBrowser:(MWPhotoBrowser *)photoBrowser didDisplayPhotoAtIndex:(NSUInteger)index
{
    _saveImg = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",_imageMutableArray[section][index]]]]];
}

//长按手势
-(void)longPressAction:(UILongPressGestureRecognizer *)ges{
    //    MWPhotoBrowser *photoBrowser = (MWPhotoBrowser*)[Utils getSuperControllerWith:ges.view];
    //只在begin执行一次
    if (ges.state == UIGestureRecognizerStateBegan) {
        NSLog(@"long pressTap state :begin");
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"保存图片到手机" style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) {
            
            UIImageWriteToSavedPhotosAlbum(self->_saveImg, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
        }];
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alertC addAction:action1];
        [alertC addAction:action2];
        [self.navigationController presentViewController:alertC animated:YES completion:nil];
    }
    
}

// 保存图片后到相册后，回调的相关方法，查看是否保存成功
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    AppDelegate *app = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:app.window animated:YES];
    //显示文字
    hud.mode = MBProgressHUDModeText;
    if (error == nil){
        hud.labelText = @"已保存到手机相册！";
        
    } else {
        hud.labelText = @"保存失败！";
    }
    // 隐藏时候从父控件中移除
    hud.removeFromSuperViewOnHide = YES;
    [hud hide:YES afterDelay:1.5];
}

#pragma mark -键盘监听方法
- (void)keyBoardWillShow:(NSNotification *)notification
{
    // 获取用户信息
    NSDictionary *userInfo = [NSDictionary dictionaryWithDictionary:notification.userInfo];
    // 获取键盘高度
    CGRect keyBoardBounds  = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyBoardHeight = keyBoardBounds.size.height;
    // 获取键盘动画时间
    CGFloat animationTime  = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    // 定义好动作
    void (^animation)(void) = ^void(void) {
        self.commentView.transform = CGAffineTransformMakeTranslation(0, -(keyBoardHeight + 50));
    };
    
    if (animationTime > 0) {
        [UIView animateWithDuration:animationTime animations:animation];
    } else {
        animation();
    }
    
}

- (void)keyBoardWillHide:(NSNotification *)notificaiton
{
    // 获取用户信息
    NSDictionary *userInfo = [NSDictionary dictionaryWithDictionary:notificaiton.userInfo];
    // 获取键盘动画时间
    CGFloat animationTime = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    // 定义好动作
    void (^animation)(void) = ^void(void) {
        self.commentView.transform = CGAffineTransformIdentity;
    };
    
    if (animationTime > 0) {
        [UIView animateWithDuration:animationTime animations:animation];
    } else {
        animation();
    }
    
}

-(void) keyBoardDidShow : (NSNotification *) notification
{
    keyBoardDidShow = YES;
}

-(void) keyBoardDidHide : (NSNotification *) notification {
    keyBoardDidShow = NO;
}

//点击空白处收起键盘
-(void)viewTapped:(UITapGestureRecognizer*)tap1
{
    isClick = NO;
    [_commentTF endEditing:YES];
}

// 监听textfield的输入以判断是否能够发布
-(void)textFieldDidChange :(UITextField *)theTextField{
    if([theTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]].length != 0) {
        [sendBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        sendBtn.backgroundColor = [UIColor colorWithRed:0.0/255 green:235.0/255 blue:0.0/255 alpha:1];
        sendBtn.layer.borderWidth = 0;
        sendBtn.enabled = YES;
    }
    else {
        [sendBtn setTitleColor:[UIColor colorWithRed:100.0/255 green:100.0/255 blue:100.0/255 alpha:1] forState:UIControlStateNormal];
        sendBtn.backgroundColor = [UIColor clearColor];
        sendBtn.layer.borderWidth = 0.5;
        sendBtn.enabled = NO;
    }
}

//发送评论并回收键盘
-(void) dismissKeyboard : (MyButton *) sendBtn {
    _comment = _commentTF.text;

    //选择更新的indexPath的行数
    //NSInteger row = sendBtn.row + 2;
    
    NSString * myName = [[NSString alloc] init];
    NSNumber * isReply = [[NSNumber alloc] init];
    NSString * contentID = [[NSString alloc] init];
    NSString * fatherID = [[NSString alloc] init];
    
    if(!isClick) {
        myName = iphoneUserName;
        isReply = @NO;
        //当前评论对应的content
        Data * content = _arrayContentData[sendBtn.section];
        NSLog(@"%@ %@", content.contentName, content.contentDetail);
        contentID = content.contentID;
        fatherID = content.userID;
    }
    else {
        myName = [NSString stringWithFormat:@"%@ 回复 %@: ", iphoneUserName, sendBtn.responseTo];
        //row = sendBtn.row;
        isReply = @YES;
        NSMutableArray * temp = _arrayCommentData[sendBtn.section];
        CommentData * comment = temp[sendBtn.row];
        contentID = comment.commentID;
        fatherID = comment.commentFatherID;
    }

    //用于上传评论数据
    dispatch_group_t downloadGroup = dispatch_group_create();
    dispatch_group_enter(downloadGroup);

    NSLog(@"%@", contentID);
    NSLog(@"%@", fatherID);
    
    NSString *url = @"http://172.18.178.56/api/comment";
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:contentID, @"contentID", fatherID, @"fatherID", _comment, @"content", isReply, @"isReply", nil];
    
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
    NSString* jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:120];
    [request setHTTPMethod:@"POST"];
    [request setValue: @"application/json; encoding=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request setValue: @"application/json" forHTTPHeaderField:@"Accept"];
    [request setHTTPBody: [jsonString dataUsingEncoding:NSUTF8StringEncoding]];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [[manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (!error && responseObject) {
            NSArray *list = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"sentComment = %@", list);
            dispatch_group_leave(downloadGroup);
        } else {
            NSLog(@"false");
        }
    }] resume];
    
    dispatch_group_notify(downloadGroup, dispatch_get_main_queue(), ^{
        NSLog(@"发送评论结束");
        [self loadData];
    });
    
    

    //停止编辑，回收键盘
    [_commentTF endEditing:YES];

    //只更新一个cell
//    NSIndexPath * indexPath = [NSIndexPath indexPathForRow:row inSection:sendBtn.section];
//    [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
    [_tableView reloadData];
    
}

//设置富文本
-(NSMutableAttributedString *) setRichTextOfName : (NSString *)strName
                             setRichTextOfComment: (NSString *)strComment
{
    //UILabel富文本显示不同颜色的字体
    // 创建Attributed
    NSMutableAttributedString *noteStr;
    
    NSInteger location1 = [strName rangeOfString:@" 回复 "].location;
    
    if(isClick && location1 != NSNotFound) {
        isClick = NO;
    }
    
    noteStr = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@", strName, strComment]];
    // 改变颜色
    [noteStr addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:0.0/255 green:102.0/255 blue:204.0/255 alpha:1] range:NSMakeRange(0, strName.length-2)];
    [noteStr addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(strName.length-2, strComment.length+2)];
    
    //设置字体字号和字体类别
    [noteStr addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"Arial" size:15.0] range:NSMakeRange(0, strName.length + strComment.length)];
    
    return noteStr;
}

//删除用户自己的评论
-(void)menuCutBtnPressed :(UIMenuItem*)menuItem
{
    NSLog(@"cut");
    
    NSNumber * section = [_cellSelectDic objectForKey:@"section"];
    NSInteger section1 = [section integerValue];
    NSNumber * row = [_cellSelectDic objectForKey:@"row"];
    NSInteger row1 = [row integerValue];
    NSNumber * commentSection = [_cellSelectDic objectForKey:@"commentSection"];
    NSInteger commentSection1 = [commentSection integerValue];
    
    NSLog(@"%ld, %ld, %ld", section1, row1, commentSection1);
    
    NSMutableArray * userCommentForEachMessage = _arrayCommentData[section1];

    CommentData * commentData = userCommentForEachMessage[commentSection1];
    
    dispatch_group_t deleteGroup = dispatch_group_create();
    dispatch_group_enter(deleteGroup);
    //获取AFHTTPSection对象
    //下载网络数据
    AFHTTPSessionManager * session = [AFHTTPSessionManager manager];
    
    NSString * path = [NSString stringWithFormat:@"http://172.18.178.56/api/comment/%@", commentData.commentID];
    [session DELETE:path parameters:nil headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if([responseObject isKindOfClass:[NSDictionary class]]) {
            NSLog(@"delete = %@", responseObject);
            dispatch_group_leave(deleteGroup);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"删除失败");
    }];
    
    dispatch_group_notify(deleteGroup, dispatch_get_main_queue(), ^{
        [userCommentForEachMessage removeObjectAtIndex:commentSection1];
        [self->_arrayCommentData replaceObjectAtIndex:section1 withObject:userCommentForEachMessage];
        
        //只更新一个cell
        //    NSIndexPath * indexPath = [NSIndexPath indexPathForRow:row1 inSection:section1];
        //    [_tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        //[self->_tableView reloadData];
        [self loadData];
    });
    
}

//对评论进行点赞
-(void) dianZanPressed : (UIMenuItem*)menuItem {
    NSNumber * section = [_cellSelectDic objectForKey:@"section"];
    NSInteger section1 = [section integerValue];
    NSNumber * commentSection = [_cellSelectDic objectForKey:@"commentSection"];
    NSInteger commentSection1 = [commentSection integerValue];
    
    NSMutableArray * array = _arrayCommentData[section1];
    CommentData * commentData = array[commentSection1];
    NSString *url = [NSString stringWithFormat:@"http://172.18.178.56/api/like/%@", commentData.commentID];
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@NO, @"isContent", @YES, @"isComment", @NO, @"isReply", nil];
    AFHTTPSessionManager * manage = [AFHTTPSessionManager manager];
    //设置请求体为JSON
    manage.requestSerializer = [AFJSONRequestSerializer serializer];
    //设置响应体为JSON
    manage.responseSerializer = [AFJSONResponseSerializer serializer];
    [manage POST:url parameters:dict headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if([responseObject isKindOfClass:[NSDictionary class]]) {
            NSLog(@"点赞评论 = %@", responseObject);
            NSString * state = [responseObject objectForKey:@"State"];
            if([state isEqualToString:@"exist"]) {
                AFHTTPSessionManager * manage1 = [AFHTTPSessionManager manager];
                //设置请求体为JSON
                manage1.requestSerializer = [AFJSONRequestSerializer serializer];
                //设置响应体为JSON
                manage1.responseSerializer = [AFJSONResponseSerializer serializer];
                [manage1 PATCH:url parameters:dict headers:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    if([responseObject isKindOfClass:[NSDictionary class]]) {
                        NSLog(@"取消点赞 = %@", responseObject);
                    }
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    NSLog(@"取消点赞失败");
                }];
            }
            else {
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"点赞失败");
    }];
    
}

//对评论进行回复
-(void) replyPress : (UIMenuItem*)menuItem {
    NSNumber * section = [_cellSelectDic objectForKey:@"section"];
    NSInteger section1 = [section integerValue];
    NSNumber * commentSection = [_cellSelectDic objectForKey:@"commentSection"];
    NSInteger commentSection1 = [commentSection integerValue];
    NSString * string = [_cellSelectDic objectForKey:@"name"];
    NSString * huifu = [NSString stringWithFormat:@"回复%@:",string];
    
    UIView *keyBoardTopView = [[UIView alloc] initWithFrame:CGRectMake(0, HZKScreenH, HZKScreenW, 50)];
    keyBoardTopView.backgroundColor = [UIColor colorWithRed:214.0/255 green:214.0/255 blue:214.0/255 alpha:1];
    keyBoardTopView.layer.borderWidth = 0.7;
    keyBoardTopView.layer.borderColor = [[UIColor colorWithRed:235.0/255 green:235.0/255 blue:235.0/255 alpha:1] CGColor];
    
    //输入框
    UITextField *inputTF = [[UITextField alloc] init];
    inputTF.frame = CGRectMake(10, 6, HZKScreenW - 10 - 76, 38);
    inputTF.placeholder = huifu;
    inputTF.tag = 1001;
    //设置代理
    inputTF.delegate = (id)self;
    inputTF.layer.cornerRadius = 4;
    inputTF.layer.masksToBounds = YES;
    self.commentTF = inputTF;
    inputTF.backgroundColor = [UIColor whiteColor];
    //监听textfield的输入
    [inputTF addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    [keyBoardTopView addSubview:inputTF];
    //让UITextField直接进入编辑状态
    [inputTF becomeFirstResponder];
    
    //发布按钮
    sendBtn = [[MyButton alloc] initWithFrame:CGRectMake(keyBoardTopView.bounds.size.width - 60 - 9, 7, 60, 36)];
    sendBtn.titleLabel.font = [UIFont boldSystemFontOfSize:17];
    [sendBtn setTitle:@"发布" forState:UIControlStateNormal];
    sendBtn.tag = 2002;
    sendBtn.backgroundColor = [UIColor clearColor];
    sendBtn.layer.borderColor = [[UIColor colorWithRed:100.0/255 green:100.0/255 blue:100.0/255 alpha:1] CGColor];
    sendBtn.layer.borderWidth = 0.5;
    sendBtn.layer.cornerRadius = 4;
    sendBtn.enabled = NO;
    [sendBtn setTitleColor:[UIColor colorWithRed:100.0/255 green:100.0/255 blue:100.0/255 alpha:1] forState:UIControlStateNormal];
    sendBtn.section = section1;
    sendBtn.row = commentSection1;
    sendBtn.responseTo = string;
    
    [sendBtn addTarget:self action:@selector(dismissKeyboard:) forControlEvents:UIControlEventTouchUpInside];
    [keyBoardTopView addSubview:sendBtn];
    
    self.commentView = keyBoardTopView;
    [self.view.superview addSubview:keyBoardTopView];

}

-(void) loadData {
    _arrayContentData = [[NSMutableArray alloc] init];
    _arrayCommentData = [[NSMutableArray alloc] init];
    _imageMutableArray = [[NSMutableArray alloc] init];
    isPraiseArray = [[NSMutableArray alloc] init];
    isCollectArray = [[NSMutableArray alloc] init];
    isCommentArray = [[NSMutableArray alloc] init];
    isDownloadArray = [[NSMutableArray alloc] init];
    _praisePeople = [[NSMutableArray alloc] init];
    _eachPraisePeople = [[NSMutableArray alloc] init];
    [self update];
}

-(void) update {
    dispatch_group_t downloadGroup0 = dispatch_group_create();
    dispatch_group_enter(downloadGroup0);
    
    NSString *url0 = @"http://172.18.178.56/api/user/login/pass";
    //    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"5fc6f311f5beb29bc39692f7", @"contentID", @"5fc48e47f5beb29bc3968c0e", @"fatherID", @"代码测试", @"content", @false, @"isReply", nil];
    NSDictionary * dict0 = @{
                             @"name" : @"605607414@qq.com",
                             @"password" : @"123456",
                             };
    NSData* jsonData0 = [NSJSONSerialization dataWithJSONObject:dict0 options:NSJSONWritingPrettyPrinted error:nil];
    NSString* jsonString0 = [[NSString alloc]initWithData:jsonData0 encoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request0 = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url0] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:120];
    [request0 setHTTPMethod:@"POST"];
    [request0 setValue: @"application/json; encoding=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request0 setValue: @"application/json" forHTTPHeaderField:@"Accept"];
    [request0 setHTTPBody: [jsonString0 dataUsingEncoding:NSUTF8StringEncoding]];
    
    AFURLSessionManager *manager0 = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    manager0.responseSerializer = [AFHTTPResponseSerializer serializer];
    [[manager0 dataTaskWithRequest:request0 uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        if (!error && responseObject) {
            NSArray *list = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"login = %@", list);
            dispatch_group_leave(downloadGroup0);
        } else {
            NSLog(@"false");
        }
        
    }] resume];
    
    dispatch_group_notify(downloadGroup0, dispatch_get_main_queue(), ^{
        dispatch_group_t downloadGroup2 = dispatch_group_create();
        dispatch_group_enter(downloadGroup2);
        //获取AFHTTPSection对象
        //下载网络数据
        AFHTTPSessionManager * session2 = [AFHTTPSessionManager manager];
        
        NSString * path2 = [NSString stringWithFormat:@"http://172.18.178.56/api/user/info/self"];
        
        //下载网络数据
        [session2 GET:path2 parameters:nil headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            NSLog(@"下载SelfInfo中");
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            //NSLog(@"下载SelfInfo成功");
            
            if([responseObject isKindOfClass:[NSDictionary class]]) {
                // NSLog(@"dic = %@", responseObject);
                [self parseSelfInfoData:responseObject];
                dispatch_group_leave(downloadGroup2);
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"下载SelfInfo失败");
        }];
        
        dispatch_group_notify(downloadGroup2, dispatch_get_main_queue(), ^{
            dispatch_group_t downloadGroup = dispatch_group_create();
            dispatch_group_enter(downloadGroup);
            //获取AFHTTPSection对象
            //下载网络数据
            AFHTTPSessionManager * session = [AFHTTPSessionManager manager];
            
            NSString * path = [NSString stringWithFormat:@"http://172.18.178.56/api/content/public?page=%ld&eachPage=10", self->page];
            
            //下载网络数据
            [session GET:path parameters:nil headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
                NSLog(@"下载content中");
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                //NSLog(@"下载content成功");
                if([responseObject isKindOfClass:[NSDictionary class]]) {
                    // NSLog(@"dic = %@", responseObject);
                    
                    [self parseContentData:responseObject];
                    dispatch_group_leave(downloadGroup);
                }
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                NSLog(@"下载content失败");
            }];
            
            dispatch_group_notify(downloadGroup, dispatch_get_main_queue(), ^{
                for(int i = 0; i < self->_arrayContentData.count; i++) {
                    CommentData * commentData = [[CommentData alloc] init];
                    commentData.haveComment = @"NO";
                    NSMutableArray * nothing = [[NSMutableArray alloc] initWithObjects:commentData, nil];
                    [self->_arrayCommentData addObject:nothing];
                    
                    NSNumber * isPraise = @NO;
                    NSNumber * isComment = @NO;
                    NSNumber * isCollect = @NO;
                    NSNumber * isDownload = @NO;
                    [self->isPraiseArray addObject:isPraise];
                    [self->isCommentArray addObject:isComment];
                    [self->isCollectArray addObject:isCollect];
                    [self->isDownloadArray addObject:isDownload];
                    
                    NSMutableArray * praisePeopletemp = [[NSMutableArray alloc] init];
                    [praisePeopletemp addObject:[NSString stringWithFormat:@"test-%d", i]];
                    [self->_praisePeople addObject:praisePeopletemp];
                }

                dispatch_group_t downloadGroup1 = dispatch_group_create();
                //获取AFHTTPSection对象
                //下载网络数据
                AFHTTPSessionManager * session = [AFHTTPSessionManager manager];
                
                for(int i = 0; i < self->_arrayContentData.count; i++) {
                    dispatch_group_enter(downloadGroup1);
                    Data * data = self->_arrayContentData[i];
                    NSString * path = [NSString stringWithFormat:@"http://172.18.178.56/api/comment/%@", data.contentID];
                    
                    //下载网络数据
                    [session GET:path parameters:nil headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
                        //NSLog(@"下载comment中");
                    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                        //NSLog(@"下载comment成功");
                        
                        if([responseObject isKindOfClass:[NSDictionary class]]) {
                            //NSLog(@"dic = %@", responseObject);
                            //NSLog(@"content: %@ %@", data.contentName, data.contentDetail);
                            [self parseCommentData:responseObject];
                        }
                        
                        dispatch_group_leave(downloadGroup1);
                        
                    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                        NSLog(@"下载comment失败");
                    }];
                }
                dispatch_group_notify(downloadGroup1, dispatch_get_main_queue(), ^{
                    [self->_tableView.mj_header endRefreshing];
                    [self->_tableView.mj_footer endRefreshing];
                    //如果已经加载到最后一页
                    [self->_tableView.mj_footer endRefreshingWithNoMoreData];
                
                    [self->_tableView reloadData];
                });
            });
        });
    });
}


//解析数据函数
-(void) parseContentData : (NSDictionary *) dicData {
    NSArray * arrData = [dicData objectForKey:@"Data"];
    
    for(NSDictionary * dicDataAndUser in arrData) {
        
        Data * data = [[Data alloc] init];
        
        NSDictionary * dicData = [dicDataAndUser objectForKey:@"Data"];
        NSString * contentID = [dicData objectForKey:@"ID"];
        // NSLog(@"%@", contentID);
        data.contentID = contentID;
        
        NSString * contentName = [dicData objectForKey:@"Name"];
        NSString * contentDetail = [dicData objectForKey:@"Detail"];
        data.contentName = contentName;
        data.contentDetail = contentDetail;
        //NSLog(@"%@", contentDetail);
        NSString * userID = [dicData objectForKey:@"OwnID"];
        data.userID = userID;
        //NSLog(@"%@", userID);
        NSString * publishTime = [dicData objectForKey:@"PublishDate"];
        data.publishTime = publishTime;
        
        NSDictionary * dicUser = [dicDataAndUser objectForKey:@"User"];
        NSString * userName = [dicUser objectForKey:@"Name"];
        //NSLog(@"%@", userName);
        data.userName = userName;
        //NSLog(@"%ld", _userNameArray.count);
        
        [_arrayContentData addObject:data];
        
        NSMutableArray * imageURLArray = [[NSMutableArray alloc] init];
        NSDictionary * dicAlbum = [dicData objectForKey:@"Album"];
        NSArray * images = [dicAlbum objectForKey:@"Images"];
        if(images.count != 0) {
            for(NSDictionary * dicImage in images) {
                NSString * thumb = [dicImage objectForKey:@"Thumb"];
                NSString * imageURL = [NSString stringWithFormat:@"http://172.18.178.56/api/thumb/%@", thumb];
                [imageURLArray addObject:imageURL];
                //NSLog(@"imageURLArray.count %ld", imageURLArray.count);
            }
        }
        else {
            NSString * str = @"noPicture";
            //NSLog(@"empty!");
            [imageURLArray addObject:str];
        }

        [_imageMutableArray addObject:imageURLArray];

    }

}

//时间戳变为格式时间
- (NSString *)ConvertStrToTime:(NSString *)timeStr
{
    //long long time=[timeStr longLongValue];
    //    如果服务器返回的是13位字符串，需要除以1000，否则显示不正确(13位其实代表的是毫秒，需要除以1000)
    long long time=[timeStr longLongValue] / 1000;
    
    NSDate *date = [[NSDate alloc]initWithTimeIntervalSince1970:time];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString*timeString=[formatter stringFromDate:date];
    
    return timeString;
    
}

-(void) parseCommentData : (NSDictionary *)dicCommentData
{
    NSMutableArray * commentAndReplyArray = [[NSMutableArray alloc] init];
    NSArray * arrData = [[NSArray alloc] init];
    CommentData * temp = [[CommentData alloc] init];
    if(![[dicCommentData objectForKey:@"Data"] isKindOfClass:[NSNull class]]) {
        arrData = [dicCommentData objectForKey:@"Data"];
        
        for(NSDictionary * dicData in arrData) {
            CommentData * commentData = [[CommentData alloc] init];
            CommentData * replyData = [[CommentData alloc] init];
            NSDictionary * dicComment = [dicData objectForKey:@"Comment"];
            NSString * commentContent = [dicComment objectForKey:@"Content"];
            NSString * commentContentID = [dicComment objectForKey:@"ContentID"];
            NSString * commentUserID = [dicComment objectForKey:@"UserID"];
            NSString * commentFatherID = [dicComment objectForKey:@"FatherID"];
            NSString * commentID = [dicComment objectForKey:@"ID"];
            commentData.commentContent = commentContent;
            commentData.commentContentID = commentContentID;
            commentData.commentUserID = commentUserID;
            commentData.commentFatherID = commentFatherID;
            commentData.commentID = commentID;
            //NSLog(@"comment: %@", commentContent);
            
            NSString * isReply = @"NO";
            commentData.isReply = isReply;
            NSString * haveComment = @"YES";
            commentData.haveComment = haveComment;
            
            NSDictionary * dicUser = [dicData objectForKey:@"User"];
            NSString * commentUserName = [dicUser objectForKey:@"Name"];
            commentData.commentUserName = commentUserName;
            //NSLog(@"%@: %@", commentUserName, commentContent);
            [commentAndReplyArray addObject:commentData];
            
            temp = commentData;
            
            if(![[dicData objectForKey:@"Replies"] isKindOfClass:[NSNull class]]) {
                NSArray * arrReplies = [[NSArray alloc] init];
                arrReplies = [dicData objectForKey:@"Replies"];
                for(NSDictionary * dicReplies in arrReplies) {
                    NSDictionary * dicReply = [dicReplies objectForKey:@"Reply"];
                    NSString * replyContent = [dicReply objectForKey:@"Content"];
                    NSString * replyContentID = [dicReply objectForKey:@"ContentID"];
                    NSString * replyUserID = [dicReply objectForKey:@"UserID"];
                    NSString * replyFatherID = [dicReply objectForKey:@"FatherID"];
                    NSString * replyID = [dicReply objectForKey:@"ID"];
                    replyData.commentContent = replyContent;
                    replyData.commentContentID = replyContentID;
                    replyData.commentUserID = replyUserID;
                    replyData.commentFatherID = replyFatherID;
                    replyData.commentID = replyID;
                    //NSLog(@"reply: %@", replyContent);
                    NSString * isReply1 = @"YES";
                    replyData.isReply = isReply1;
                    NSString * haveComment1 = @"YES";
                    replyData.haveComment = haveComment1;
                    
                    NSDictionary * dicReplyUser = [dicReplies objectForKey:@"User"];
                    NSString * replyUserName = [dicReplyUser objectForKey:@"Name"];
                    replyData.commentUserName = replyUserName;
                    
                    replyData.replyFatherName = commentUserName;
                    //NSLog(@"%@ 回复 %@: %@", replyUserName, commentUserName, replyContent);
                    [commentAndReplyArray addObject:replyData];
                }
            }
        }
    }
    else {
        CommentData * commentData = [[CommentData alloc] init];
        commentData.haveComment = @"NO";
        [commentAndReplyArray addObject:commentData];
    }
    
    for(int j = 0; j < _arrayContentData.count; j++) {
        Data * data = _arrayContentData[j];
        if([temp.commentContentID isEqualToString:data.contentID]) {
            [_arrayCommentData replaceObjectAtIndex:j withObject:commentAndReplyArray];
            break;
        }
    }
}

-(void) parseSelfInfoData : (NSDictionary *)dicCommentData {
    NSDictionary * dicInfo = [dicCommentData objectForKey:@"Info"];
    NSString * name = [dicInfo objectForKey:@"Name"];
    iphoneUserName = name;
}


@end
